from flask import jsonify, request, render_template, flash
from app.libs.helper import is_isbn_or_key
from app.spider.ys_book import YsBook
from . import web
from app.forms.book import SearchFrom
from app.view_models.book import BookCollection, BookViewModel
from app.models.gift import Gift
from app.models.wish import Wish
from app.view_models.trade import TradeInfo
from flask_login import current_user
import json

"""
书籍视图模块
"""


@web.route('/test')
def test():
    r = {
        'name': 'tom',
        'age': 18
    }
    flash('hello,world', category='error')
    flash('hello,jim', category='waring')
    return render_template('test3.html', data=r)


# @web.route('/test')
# def test():
#     from flask import request
#     from app.libs.nolocal import n
#     print(n.v)
#     n.v = 2
#     print('---------------')
#     print(getattr(request, 'v', None))
#     setattr(request, 'v', 2)
#     print(request.v)
#     return ''


# 注册视图函数到蓝图
@web.route('/book/search')
def search():
    """
    书籍名或isbn搜索
    :param q:关键字
    :param page: 页码
    :return:
    """
    # 表单验证
    form = SearchFrom(request.args)
    books = BookCollection()

    if form.validate():
        q = form.q.data.strip()
        page = form.page.data
        # 关键字判断
        isbn_or_key = is_isbn_or_key(q)
        ys_book = YsBook()

        if isbn_or_key == 'isbn':
            ys_book.search_by_isbn(q)
        else:
            ys_book.search_by_keyword(q, page)

        books.fill(ys_book, q)
        # return json.dumps(books, default=lambda o: o.__dict__)
    else:
        flash('搜索的关键字不符合要求，请重新输入')
        # return jsonify(form.errors)
    return render_template('search_result.html', books=books, form=form)


@web.route('/book/<isbn>/detail')
def book_detail(isbn):
    # 书籍详情数据
    ys_book = YsBook()
    ys_book.search_by_isbn(isbn)
    book = BookViewModel(ys_book.first)
    # 书籍的赠送者数据
    trade_gifts = Gift.query.filter_by(isbn=isbn, launched=False).all()
    trade_gifts_model = TradeInfo(trade_gifts)
    # 书籍的索要者数据
    trade_wishes = Wish.query.filter_by(isbn=isbn, launched=False).all()
    trade_wishes_model = TradeInfo(trade_wishes)
    # 用户是否是书籍的赠送者或索要者
    has_in_gifts = False
    has_in_wishes = False
    if current_user.is_authenticated:
        has_in_gifts = True if Gift.query.filter_by(
            uid=current_user.id, isbn=isbn, launched=False
        ).first() else False
        has_in_wishes = True if Wish.query.filter_by(
            uid=current_user.id, isbn=isbn, launched=False
        ).first() else False

    return render_template(
        'book_detail.html', book=book,
        wishes=trade_wishes_model, gifts=trade_gifts_model,
        has_in_gifts=has_in_gifts, has_in_wishes=has_in_wishes
    )
